package zjc.bookkeeping.fragment.statistics;

import android.graphics.Color;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.dld.view.SegmentedControlItem;
import com.dld.view.SegmentedControlView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import zjc.bookkeeping.R;
import zjc.bookkeeping.db.DBManager;
import zjc.bookkeeping.db.MethodBean;
import zjc.bookkeeping.fragment.tools.MyPercentFormatter;
import zjc.bookkeeping.fragment.tools.XYMarkerView;


public class StatisticsWeekFragment extends Fragment {
    private View fragment_statistics_week;
    private CardView week_view;
    private CardView cardView1;
    private CardView cardView2;
    private CardView cardView3;
    private BarChart chart;
    private PieChart chart3;
    private SegmentedControlView mscv;
    private TextView total_expenditure;
    private TextView total_income;
    private TextView average_daily_expenditure;
    private TextView average_daily_income;
    private static final String TAG = "???";
    private ArrayList<BarEntry> values0 = new ArrayList<>();//支出
    private ArrayList<BarEntry> values1 = new ArrayList<>();//收入
    private ListView class_list;
    private final RectF onValueSelectedRectF = new RectF();
    private BarDataSet dataSets;
    private List<WeekClassListData> weekClassListData = new ArrayList<>();
    private int listviewElementsheight = 0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        fragment_statistics_week = inflater.inflate(R.layout.fragment_statistics_week, container, false);
        findView();//绑定控件
        getSevenDatas();
        chart(0);//柱形图 近7日统计
        //lineChart();//折线图
        switchChange();//支出收入切换开关
        pieChart();//饼状图
        Adaptation();
        //System.out.println("分类" + DBManager.getAllConsumptionClass());
        return fragment_statistics_week;
    }

    // 适配处理
    public void Adaptation(){
        //获取屏幕宽度
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        //定义布局参数
        Log.i("width",String.valueOf(width * 0.9));
        Log.i("height",String.valueOf(height * 0.28));
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.width = (int) (width * 0.9);
        layoutParams.height = (int) (width * 0.9 * 0.618);
        Log.e("height2", String.valueOf(layoutParams.height));
        layoutParams.topMargin = (int) (width * 0.05);
        layoutParams.leftMargin = (int) (width * 0.05);
        layoutParams.rightMargin = (int) (width * 0.05);
        cardView1.setLayoutParams(layoutParams);

        LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams2.width = (int) (width * 0.9);
        Log.e("listviewElementsheight", String.valueOf(listviewElementsheight));
        layoutParams2.height = (listviewElementsheight < width*0.9*0.618)?(int) (width * 0.9 * 0.618):(int) (listviewElementsheight);
        layoutParams2.topMargin = (int) (width * 0.05);
        layoutParams2.leftMargin = (int) (width * 0.05);
        layoutParams2.rightMargin = (int) (width * 0.05);
        cardView2.setLayoutParams(layoutParams2);

        LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams3.width = (int) (width * 0.9);
        layoutParams3.height = (int) (width * 0.9 * 0.718);
        layoutParams3.topMargin = (int) (width * 0.05);
        layoutParams3.leftMargin = (int) (width * 0.05);
        layoutParams3.rightMargin = (int) (width * 0.05);
        layoutParams3.bottomMargin = (int) (width * 0.08);
        cardView3.setLayoutParams(layoutParams3);


        LinearLayout.LayoutParams layoutParams4 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutParams4.width = (int) (width * 0.9);
        layoutParams4.height = (int) (width * 0.9 * 0.6);
        layoutParams4.topMargin = (int) (-width * 0.05);
        layoutParams4.bottomMargin = (int) (width * 0.08);
        chart3.setLayoutParams(layoutParams4);

    }



    // 支出/收入切换开关
    public void switchChange(){
        List<SegmentedControlItem> filesType = createFilesType();
        mscv.addItems(filesType);
        mscv.setSelectedItem(0);//默认为第一项支出
        mscv.setOnSegItemClickListener(new SegmentedControlView.OnSegItemClickListener() {
            @Override
            public void onItemClick(SegmentedControlItem item, int position) {
                String msg = String.format(Locale.getDefault(), "click scv selected:%d", position);
                // 数据更新
                chart.removeAllViews();
                //BarDataSet dataSets;
                if (position == 1){
                    dataSets.setValues(values1);
                    chart.getAxisLeft().setEnabled(!isDataNull(values1));
                    //dataSets = new BarDataSet(values1,"");
                } else {
                    dataSets.setValues(values0);
                    chart.getAxisLeft().setEnabled(!isDataNull(values0));
                    //dataSets = new BarDataSet(values0,"");
                }
                //dataSets.setColor(Color.parseColor("#E5F3F8"));//改变柱形图颜色
                BarData data = new BarData(dataSets);
                data.setValueTextSize(10f);//数据字体大小
                data.setBarWidth(0.3f);
                chart.setData(data);// 加入数据
                chart.highlightValue(null);
            }
        });
    }

    public boolean isDataNull(ArrayList<BarEntry> entries){
        for (BarEntry entry: entries) {
            if (entry.getY() != 0){
                return false;
            }
        }
        return true;
    }

    // 绑定控件
    @RequiresApi(api = Build.VERSION_CODES.P)
    public void findView(){
        cardView1 = fragment_statistics_week.findViewById(R.id.cardview1);
        cardView2 = fragment_statistics_week.findViewById(R.id.cardview2);
        cardView3 = fragment_statistics_week.findViewById(R.id.cardview3);
        week_view = fragment_statistics_week.findViewById(R.id.week_view);
        chart = fragment_statistics_week.findViewById(R.id.chart1);
        mscv = fragment_statistics_week.findViewById(R.id.scv);
       // chart2 = fragment_statistics_week.findViewById(R.id.chart2);
        chart3 = fragment_statistics_week.findViewById(R.id.chart3);
        total_expenditure = fragment_statistics_week.findViewById(R.id.total_expenditure);
        total_income = fragment_statistics_week.findViewById(R.id.total_income);
        average_daily_expenditure = fragment_statistics_week.findViewById(R.id.average_daily_expenditure);
        average_daily_income = fragment_statistics_week.findViewById(R.id.average_daily_income);
        class_list = fragment_statistics_week.findViewById(R.id.class_list);
        class_list.setEmptyView(fragment_statistics_week.findViewById(R.id.empty_view));
        ListData();
        WeekClassListAdapter adapter = new WeekClassListAdapter(getContext(),getWeekSumConsumption(),weekClassListData);
        Log.i("sum", String.valueOf(getWeekSumConsumption()));
        class_list.setAdapter(adapter);
        if (adapter.getCount() > 0){
            for (int i = 0; i < adapter.getCount(); i++) {
                View mView = adapter.getView(i, null, class_list);
                mView.measure(
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                listviewElementsheight += mView.getMeasuredHeight();
            }
            listviewElementsheight = (int) (listviewElementsheight / (adapter.getCount() + 1) * (adapter.getCount() + 2.3));
            Log.e("height", String.valueOf(listviewElementsheight));
        }

    }

    public void ListData(){
        List<String> classes_name = DBManager.getAllConsumptionClass();
        float class_week_sum = 0;
        int sum = 0;
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf1 = new SimpleDateFormat("MM");
        SimpleDateFormat sdf2 = new SimpleDateFormat("dd");
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w == 0)
            w = 7;
        for (int j = 0; j < classes_name.size(); j ++){
            class_week_sum = 0;
            sum = 0;
        for (int i = 1; i <= w; i++) {
            Date today = new Date(System.currentTimeMillis() - (w - i) * 1000 * 60 * 60 * 24);
            int year = Integer.valueOf(sdf0.format(today));
            int month = Integer.valueOf(sdf1.format(today));
            int day = Integer.valueOf(sdf2.format(today));
            float dayClassComsumption = DBManager.getDayClassConsumption(year, month, day, classes_name.get(j));
            class_week_sum += dayClassComsumption;
            sum += DBManager.getDayClassSum(year, month, day, classes_name.get(j));
        }
        if (class_week_sum != 0) weekClassListData.add(new WeekClassListData(classes_name.get(j),class_week_sum,sum));
        }
    }

    public void pieChart(){
        chart3.setUsePercentValues(true);
        chart3.setNoDataText("暂无数据");
        chart3.getDescription().setEnabled(false);
        chart3.setExtraOffsets(5, 10, 5, 5);

        chart3.setDragDecelerationFrictionCoef(0.95f);


        chart3.setDrawHoleEnabled(true);
        chart3.setHoleColor(Color.WHITE);

        chart3.setTransparentCircleColor(Color.WHITE);
        chart3.setTransparentCircleAlpha(110);

        chart3.setHoleRadius(58f);
        chart3.setTransparentCircleRadius(61f);

        chart3.setDrawCenterText(true);

        chart3.setRotationAngle(0);
        chart3.setRotationEnabled(true);
        chart3.setHighlightPerTapEnabled(true);

        chart3.animateY(1400, Easing.EaseInOutQuad);

        // entry label styling
        chart3.setEntryLabelColor(Color.parseColor("#ff999999"));
       // chart3.setEntryLabelTypeface(tfRegular);
        chart3.setEntryLabelTextSize(0f);

        ArrayList<PieEntry> entries = new ArrayList<>();
        List<MethodBean> allMethod = DBManager.getAllMethod();
        int length = allMethod.size();
        ArrayList<String> method_name = new ArrayList<>();
        ArrayList<Float> method_money = new ArrayList<>();
        for (int i = 0; i < length; i ++){
            float temp = allMethod.get(i).getMethod_money();
            if (temp != 0){
                method_name.add(allMethod.get(i).getMethod_name());
                method_money.add(allMethod.get(i).getMethod_money());
            }
        }
        int length2 = method_money.size();
        final String[] parties = new String[length2];
        for (int i = 0; i < length2; i ++){
            //Log.i("账户",allMethod.get(i).getMethod_name());
            parties[i] = method_name.get(i);
            entries.add(new PieEntry((method_money.get(i)),
                    parties[i % parties.length]));
        }

//
        Legend l = chart3.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);
        PieDataSet dataSet = new PieDataSet(entries, "");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);
        dataSet.setValueLinePart1OffsetPercentage(80.f);
        dataSet.setValueLinePart1Length(0.4f);
        dataSet.setValueLinePart2Length(0.4f);
        //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setValueLineColor(Color.parseColor("#ff999999"));


        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setDrawValues(true);
        data.setValueFormatter(new MyPercentFormatter(chart3));
        data.setValueTextSize(8f);
        data.setValueTextColor(Color.parseColor("#ff999999"));
       // data.setValueTypeface(tfLight);
        chart3.setData(data);

        // undo all highlights
        chart3.highlightValues(null);

        chart3.invalidate();
        if (length2 == 0){
            Log.e("data","null");
            chart3.setCenterText("暂无数据");
        }else {
            chart3.setCenterText("总资产" + "\n" + String.valueOf(DBManager.getAllMethodMoney()));
        }
        chart3.setNoDataText("暂无数据");
        chart3.setCenterTextColor(Color.parseColor("#ff999999"));


        chart3.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                PieEntry p = (PieEntry) e;
                Log.e("entry", p.getLabel());
                chart3.setCenterText(p.getLabel() + "\n" + String.valueOf(e.getY()));
            }

            @Override
            public void onNothingSelected() {
                chart3.setCenterText("总资产" + "\n" + String.valueOf(DBManager.getAllMethodMoney()));
            }
        });
    }





    private List<SegmentedControlItem> createFilesType(){
        List<SegmentedControlItem> items = new ArrayList<>();
        items.add(new SegmentedControlItem(getResources().getString(R.string.expenses)));
        items.add(new SegmentedControlItem(getResources().getString(R.string.income)));
        return items;
    }

    // 近7日统计
    private void chart(int kind){
        //chart.setOnChartValueSelectedListener(this);
        //chart.getAxisLeft().setEnabled(true);//隐藏y轴左侧
        chart.getAxisRight().setEnabled(false);//隐藏y轴右侧
        chart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);//x轴位置
        chart.getXAxis().setDrawAxisLine(true);
        chart.getAxisLeft().setAxisMinimum(0);
        chart.setScaleEnabled(false);

        chart.setDrawBarShadow(false);//隐藏阴影
        chart.setDrawValueAboveBar(true);
        chart.getXAxis().setDrawGridLines(false);//去掉柱状图背后的竖线
        chart.getAxisLeft().setDrawGridLines(false);
        chart.getDescription().setEnabled(false);//禁用描述
        chart.getLegend().setEnabled(false);//禁用图例
        chart.setPinchZoom(false);
        chart.setDrawGridBackground(false);


        // 横坐标显示近7天日期
        Date date=new Date();
        System.out.println(date);
        SimpleDateFormat dateFormat=new SimpleDateFormat("MM-dd");//设置当前时间的格式，为月-日
        final String[] xLabels = new String[7];//从0-6依次存放日期 从最远的到最近的一天
        for (int i = 0; i < 7; i++){
            Date today = new Date(System.currentTimeMillis() - i * 1000 * 60 * 60 * 24);
            String before_date = dateFormat.format(today);
           // System.out.println(before_date);// 3.3-2.25
            xLabels[7-i-1] = before_date;//6-0
        }

        // x坐标轴显示
        XAxis xAxis = chart.getXAxis();
        xAxis.setTextSize(10f);//x轴字体大小
        xAxis.setValueFormatter(new ValueFormatter() {   //X轴自定义标签内容
            @Override
            // index从1开始 作为数组下标-1     1-7
            public String getAxisLabel(float index, AxisBase axisBase) {
                //Log.i("index", String.valueOf(index));
                return xLabels[(int)(index-1)];
            }
        });


        chart.getAxisLeft().setEnabled(!isDataNull(values0));
        dataSets = new BarDataSet(values0,"");
        dataSets.setColor(Color.parseColor("#C5E0FB"));//改变柱形图颜色

        dataSets.setDrawValues(false);
        //Color.parseColor("#5E80BF")  getResources().getColor(R.color.blue_5C97D6)
        dataSets.setHighLightColor(Color.parseColor("#5E80BF"));
        BarData data = new BarData(dataSets);
        data.setValueTextSize(10f);//数据字体大小
        data.setBarWidth(0.3f);

       chart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
           @Override
           public void onValueSelected(Entry e, Highlight h) {
               BarEntry barEntry = (BarEntry) e;
               if (e == null)
                   return;


//               Highlight highlight = new Highlight(50f, 0);
//
//               chart.highlightValue(highlight, false);

               RectF bounds = onValueSelectedRectF;
               chart.getBarBounds((BarEntry) e, bounds);
               MPPointF position = chart.getPosition(e, YAxis.AxisDependency.LEFT);

               Log.i("bounds", bounds.toString());
               Log.i("position", position.toString());
               Log.i("x-index",
                       "low: " + chart.getLowestVisibleX() + ", high: "
                               + chart.getHighestVisibleX());
               MPPointF.recycleInstance(position);
               System.out.println("点击后获取的值：" + barEntry.getY());
           }

           @Override
           public void onNothingSelected() {

           }
       });
        chart.removeAllViews();
        chart.setData(data);// 加入数据
        XYMarkerView mv = new XYMarkerView(getContext());
        mv.setChartView(chart); // For bounds control
        chart.setMarker(mv);
        chart.getAxisLeft().setLabelCount(5);
    }



    // 七日数据查询+存储
    private void getSevenDatas(){
        // 年 月 日
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf1 = new SimpleDateFormat("MM");
        SimpleDateFormat sdf2= new SimpleDateFormat("dd");

        float sum_income = 0;
        float sum_expend = 0;
        // 横坐标 近7天的支出/收入数据
        for (int i = 6; i >= 0; i--) {
            //从最近一天倒着存到最远的一天
            Date today = new Date(System.currentTimeMillis() - i * 1000 * 60 * 60 * 24);
            int year = Integer.valueOf(sdf0.format(today));
            int month = Integer.valueOf(sdf1.format(today));
            int day = Integer.valueOf(sdf2.format(today));
            // 支出
            float val0 = DBManager.getDaySumConsumption(year,month,day,0);
            values0.add(new BarEntry(7-i,val0));
            sum_expend += val0;
            // 收入
            float val1 = DBManager.getDaySumConsumption(year,month,day,1);
            values1.add(new BarEntry(7-i,val1));
            sum_income += val1;
        }

        float average_income = sum_income / 7;
        float average_expend = sum_expend / 7;

        DecimalFormat df = new DecimalFormat("#0.00");// 保留两位小数

        //底部数据统计
        total_expenditure.setText(df.format(sum_expend));
        total_income.setText(df.format(sum_income));
        average_daily_income.setText(df.format(average_income));
        average_daily_expenditure.setText(df.format(average_expend));
    }

    public float getWeekSumConsumption(){
        float week_sum = 0;
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf1 = new SimpleDateFormat("MM");
        SimpleDateFormat sdf2= new SimpleDateFormat("dd");
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w == 0) w = 7;
        for (int i = 1; i <= w; i++){
            Date today = new Date(System.currentTimeMillis() - (w - i) * 1000 * 60 * 60 * 24);
            int year = Integer.valueOf(sdf0.format(today));
            int month = Integer.valueOf(sdf1.format(today));
            int day = Integer.valueOf(sdf2.format(today));
            float dayComsumption = DBManager.getDaySumConsumption(year, month, day,0);
            week_sum += dayComsumption;
            Log.i("day",String.valueOf(dayComsumption));
        }
        return week_sum;
    }


}